package com.base.monitor.module.biz.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@RefreshScope
public class TcpServer {

    @Autowired
    private ReceiveDataHandler receiveDataHandler;

    private Channel serverChannel;

    /** 关闭当前server */
    public void closeServer() {
        if (serverChannel != null) {
            log.info("tcp服务器已经关闭");
            serverChannel.close();
            serverChannel = null;
        }
    }

    /**
     * 启动服务器
     * @param port 端口号
     */
    public void startServer(int port) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {//创建通道初始化对象，设置初始化参数

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HexDecoder());
                            ch.pipeline().addLast(new StringEncoder());
//                            ch.pipeline().addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
                            ch.pipeline().addLast(receiveDataHandler);
                        }
                    });
            ChannelFuture cf = bootstrap.bind(port).sync();
            serverChannel = cf.channel();
            log.info("服务器启动成功，监听端口{}", port);
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            log.info("服务器启动失败，程序关闭，原因是：{}", e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
